package com.hqq.concurrency.mutex;

/**
 * Jar
 * Mutex锁保证jar只可以被单个Thief线程访问
 * Created by heqianqian on 2017/7/29.
 */
public class Jar {

    private final Lock lock;

    private int beans;

    public Jar(Lock lock, int beans) {
        this.lock = lock;
        this.beans = beans;
    }

    public boolean takeBean() {
        boolean success = false;
        try {
            lock.acquire();
            success = beans > 0;
            if (success) {
                beans -= 1;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.release();
        }
        return success;
    }
}
